package com.itheima.web;

import com.itheima.entity.Result;
import com.itheima.pojo.Goods;
import com.itheima.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@CrossOrigin(origins = "*")
public class GoodsController{
    @Autowired
    private GoodsService goodsService;
    //1查询所有
    @GetMapping("/goods")
    public Result<List<Goods>> findAll(){
        List<Goods> goodsList = goodsService.findAll();
        if (null!=goodsList) {
            return new Result(true,"查询成功",goodsList);
        }
        return new Result<List<Goods>>(false,"查询失败");
    }
    //添加商品
    @PostMapping("/goods")
    public Result add(Goods goods){
        boolean add = goodsService.add(goods);
        if (add){
            return new Result(true,"添加成功");
        }
        return new Result(false,"添加失败");
    }
    //分页查询商品
    @GetMapping("/goods/search/{page}/{size}")
    public Result findPageByGet(@PathVariable("page")Integer page,@PathVariable("size")Integer size){
        List<Goods> goodsList = goodsService.findPage(page, size);
        if (null==goodsList&&goodsList.size()<1){
            return new Result<>(false,"查询失败");
        }
        return new Result<>(true,"查询成功",goodsList);
    }
    //分页查询商品
    @PostMapping("/goods/search/{page}/{size}")
    public Result findPageByPost(@PathVariable("page")Integer page,@PathVariable("size")Integer size){
        List<Goods> goodsList = goodsService.findPage(page, size);
        if (null==goodsList&&goodsList.size()<1){
            return new Result<>(false,"查询失败");
        }
        return new Result<>(true,"查询成功",goodsList);
    }

    //根据id查询商品
    @GetMapping("/goods/{id}")
    public Result<Goods> findById(@PathVariable("id") Integer id){
        if(id==null){
            return new Result<>(false,"查询失败，id不存在");
        }
        Goods goods = goodsService.findById(id);
        if (goods == null) {
            return new Result<>(false,"查询失败");
        }
        return new Result<>(true,"查询成功",goods);
    }

    //post请求分页查询
    @PutMapping("/goods/{id}")
    public Result<Boolean> update(@PathVariable("id")Integer id,@RequestBody Goods goods){
        boolean result = goodsService.update(id,goods);
        if (result) {
            return new Result<Boolean>(true,"更新成功");
        }
        return new Result<Boolean>(false,"更新失败");
    }
    //删除商品
    @DeleteMapping("/goods/{id}")
    public Result delete(@PathVariable("id") Integer id){
        boolean result = goodsService.delete(id);
        if(result){
            return new Result(true, "删除成功");
        }
        return new Result(false,"删除失败");
    }

}
